package com.atguigu.day1;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicket {
    private Integer ticketCount = 50;

    public Integer getTicketCount() {
        return ticketCount;
    }

    public void setTicketCount(Integer ticketCount) {
        this.ticketCount = ticketCount;
    }
    //同步方法
/*    public synchronized void buyTicket() {
        if (ticketCount > 0) {
            System.out.println(Thread.currentThread().getName() + "\t" + "卖出第" + (ticketCount--) + "张票" + "\t 还剩下：" + ticketCount);
        }
    }*/

    //同步代码快
/*    public void buyTicket(){
        synchronized (Object.class){
            if (ticketCount > 0) {
                System.out.println(Thread.currentThread().getName() + "\t" + "卖出第" + (ticketCount--) + "张票" + "\t 还剩下：" + ticketCount);
            }
        }
    }*/

    //加Lock锁,创建lock锁的卖票方法
    private final Lock lock = new ReentrantLock(true);//加个true变成公平锁，默认是false非公平锁

    public void buyTicket() {
        lock.lock();
            try {
                if (ticketCount > 0) {
                    System.out.println(Thread.currentThread().getName() + "\t" + "卖出第" + (ticketCount--) + "张票" + "\t 还剩下：" + ticketCount);
                }
            } finally {
                lock.unlock();
            }

    }
}
